<template>
  <div class="issues-main" v-loading="loading">
    <div class="issues-wrap left">
      <!-- 标题 -->
      <div class="left-title">
        <div class="icon"></div>
        <h3>新建 通知公告</h3>
      </div>
      <el-form :model="form" ref="ruleFormRef" status-icon :rules="rules">
        <el-form-item prop="data_title">
          <el-input
            size="large"
            maxlength="200"
            show-word-limit
            v-model="form.data_title"
            placeholder="标题"
          />
        </el-form-item>
      </el-form>
      <!-- 富文本编辑器 -->
      <div class="issues-wrap editer">
        <IssuesEditor :issuesData="form"></IssuesEditor>
        <div class="button">
          <el-button
            size="large"
            color="#6C52EA"
            type="warning"
            plain
            @click.stop="handleSave(pageId)"
            >{{ pageId ? '保存' : '创建' }}</el-button
          >
          <el-button size="large" @click="handleBack" plain>{{
            pageId ? '取消' : '返回'
          }}</el-button>
        </div>
      </div>
    </div>
    <div class="issues-wrap right">
      <div class="issues-wrap content">
        <div class="right-title">
          <el-tooltip effect="dark" content="返回">
            <el-button @click.stop="handleBack" text>
              <svg class="action-icon" aria-hidden="true" width="18" height="18">
                <use xlink:href="#iconzuojiantou" fill="#409eff" />
              </svg>
            </el-button>
          </el-tooltip>
        </div>
        <RightForm
          @send-tagsDialog="handleDialog"
          @change="change"
          :form="form"
          :rules="rules"
          :defaultTopValue="defaultTopValue"
        >
        </RightForm>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { LocationQuery, useRouter } from 'vue-router'
// import { setting } from '@/utils/setting'
// import { newIssuesData, getIssuesList, editIssuesData } from '@/apis/issues/issues-lists'
// import { Issues } from '@/views/issues/config/issues'
import { ElMessage, FormRules } from 'element-plus'
import Editor from '@tinymce/tinymce-vue'
import AddTags from './component/AddTags.vue'
import IssuesEditor from './components/IssuesEditor.vue'
import RightForm from './components/RightForm.vue'
import { newNoticeData, editNoticeData, getNoticeList } from '@/apis/system/notice'
// import { newRecipientData } from '@/apis/homepage/recipient'
import Router from '@/router'
import { Itype } from '@/type'
import { INotices } from '@/views/noticeManagement/config/notice'

const defaultTopValue = ref('0')
const rules = reactive<FormRules>({
  type: [{ required: true, message: '公告类型不能为空', trigger: 'blur' }],
  data_title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  recipient: [{ required: true, message: '接收人不能为空', trigger: 'blur' }]
})
const emit = defineEmits(['dialogClose', 'dialogSave', 'handleSave'])

let form = ref<INotices>({
  _id: 0,
  data_title: '', // 公告标题
  data_content: '', // 公告内容
  recipient_id: [],
  type: '', // 类型
  priority: '', // 优先级
  time_range: [], // 时间范围
  created_at: ''
})

/**
 * @desc: 创建公告
 */
const createData = (form: INotices) => {
  newNoticeData(form)
    .then((res) => {
      if (!res) return
      //   let noticeId = res.data.id
      //   createRecipient(noticeId)
      handleBack()
      ElMessage.success('创建成功')
    })
    .catch(() => {
      ElMessage('服务器内部错误@@@')
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * @desc:获取公告数据
 *
 */
const $router = useRouter()
const pageId = ref<number>(+$router.currentRoute.value.query.id!)
const loading = ref(false)
let dataLists: Itype = ref()
const getData = () => {
  loading.value = true
  getNoticeList({
    id: pageId.value
  })
    .then((res) => {
      if (res) {
        if (!res.rows) return
        res.rows.forEach((element: INotices) => {
          element.created_at = new Date(
            +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
          )
            .toISOString()
            .replace(/T/g, ' ')
            .replace(/\.[\d]{3}Z/, '')
        })
        form.value = res.rows[0]
        loading.value = false
      }
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

if (!!pageId.value) {
  getData()
}

/**
 * @desc: 创建接收人
 */
// const createRecipient = (id: number) => {
//   let notice_id = id
//   let arr: any[] = []
//   for (let i = 0; i < recipient.value.length; i++) {
//     arr.push({ user_id: recipient.value[i], notice_id: id })
//   }
//   const reqData = {
//     __method_name__: 'batchCreate',
//     object_uuid: 'object639030296f746',
//     view_uuid: 'view639034125c3ad',
//     batch_data: arr,
//     transcode: 0
//   }
//   newRecipientData(reqData, notice_id)
//     .then((res) => {
//       if (res.code !== 200) return
//     })
//     .catch(() => {
//       ElMessage('服务器内部错误')
//     })
//     .finally(() => {
//       loading.value = false
//     })
// }
/**
 * @desc: 增加标签
 */
const tagsDialog = ref(false)
const handleDialog = () => {
  tagsDialog.value = true
}
/**
 * @desc: 修改公告
 */
const editData = (id: number) => {
  editNoticeData(form.value)
    .then((res) => {
      if (!res) return
      // let noticeId = res.data.id
      // createRecipient(noticeId)
      handleBack()
      ElMessage.success('修改成功')
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * @desc: 保存
 */
const ruleFormRef = ref()
const handleSave = (id: number) => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      if (id) {
        form.value._id = id
        editData(id)
      } else {
        createData(form.value)
      }
    }
  })
}
/**
 * @desc: 选择框
 */
const recipient = ref([])
const change = (data: []) => {
  recipient.value = data
}
/**
 * @desc: 后退
 */
const handleBack = () => {
  Router.back()
}
</script>

<style lang="less" scoped>
@color: #fdf6ec;

.button {
  position: absolute;
  bottom: 5%;
  right: 4%;
  .cancel {
    color: #dcd0ff;
  }
}
.issues-main {
  position: relative;
  display: flex;
  overflow: auto;
  padding: 10px;
  background: #fff;
  border-radius: 10px;
  .left {
    width: 70%;
    .left-title {
      display: flex;
      align-items: center;
      padding-bottom: 20px;

      .icon {
        height: 26px;
        width: 6px;
        margin-right: 16px;
        box-sizing: border-box;
        background: #409eff;
        border-radius: 3px;
      }
    }
  }
  .right {
    flex: 1;
    .content {
      margin-left: 20px;
      .right-title {
        display: flex;
        justify-content: flex-end;
        height: 26px;
        padding-bottom: 20px;
        line-height: 26px;
      }
    }
  }
  .el-button--large {
    margin-top: 20px;
  }
}
</style>
